
#pragma once

#include "index.hpp"
#include "util.hpp"
#include "Log.hpp"
#include <algorithm>
#include <unordered_map>
#include <jsoncpp/json/json.h>
namespace ns_searcher
{
  struct InvertedElemPrint
  {
    uint64_t doc_id;
    int weight;
    std::vector<std::string> words;
    InvertedElemPrint()
      :doc_id(0),weight(0)
    {}
  };

  class Searcher
  {
    private:
      ns_index::Index* index;//提供查找需要的索引
    public:
      Searcher(){}
      ~Searcher(){}
    public:                                                                       
      void InitSearcher(const std::string& input)
      {
      	//1.获取或者创建index对象
			  index = ns_index::Index::GetInstance();
			  LOG(INFO,"获取index单例成功...");
			  //2.根据index对象创建索引
			  index->BuildIndex(input);
			  LOG(INFO,"建立正排和倒排索引成功...");
      }
      //query:搜索关键词
      //json_string：返回搜索结果
	  void Search(const std::string& query,std::string*json_string)
    {
      //1.对搜索关键词进行分词
      std::vector<std::string> words;
      ns_util::JiebaUtil::CutString(query,&words);
      //2.根据分词进行index查找
      std::vector<InvertedElemPrint> inverted_list_all;

      std::unordered_map<uint64_t,InvertedElemPrint> tokens_map;

      for(std::string word:words)
      {
        boost::to_lower(word);

        ns_index::InvertedList* inverted_list = index->GetInvertedList(word);
        if(nullptr == inverted_list)
        {
          continue;
        }
        for(const auto&elem:*inverted_list)
        {
          auto& item = tokens_map[elem.doc_id];

          item.doc_id = elem.doc_id;
          item.weight += elem.weight;
          item.words.push_back(elem.word);
        }
      }
      for(const auto&item:tokens_map)
      {
        inverted_list_all.push_back(std::move(item.second));
      }
      //3.汇总查找结果，按照权重weight来排降序
      std::sort(inverted_list_all.begin(),inverted_list_all.end(),\
          [](const InvertedElemPrint&e1,const InvertedElemPrint&e2)
          {
          return e1.weight>e2.weight;
          });
      //4.根据查找出来的结果，进行序列化，构建json串
      Json::Value root;
      for(auto& item:inverted_list_all)
      {
        ns_index::DocInfo* doc = index->GetForwardIndex(item.doc_id);
        if(nullptr == doc)
        {
          continue;
        }
        Json::Value elem;
        elem["title"] = doc->title;
        elem["desc"] = GetDesc(doc->content,item.words[0]);
        elem["url"] = doc->url;
        elem["id"] = (int)item.doc_id;
        elem["weight"] = item.weight;

        root.append(elem);
      }
      Json::StyledWriter write;
      *json_string = write.write(root);
    }
  
	  std::string GetDesc(const std::string& html_content,const std::string&word)
    {
      //节选部分内容
      const int prev_step = 50;
      const int next_step = 100;

      //1.找到首次出现的位置
      auto iter = std::search(html_content.begin(),html_content.end(),word.begin(),word.end(),[](int x,int y)
          {
          return (std::tolower(x) == std::tolower(y));
          });
      if(iter == html_content.end())
      {
        return "None1";
      }
      int pos = std::distance(html_content.begin(),iter);

      //2.获取start，end下标
      int start = 0;
      int end = html_content.size() - 1;
      //判断前方是否有足够字符
      if(pos>start+prev_step) start = pos - prev_step;
      if(pos<end-next_step) end = pos+next_step;

      // 3.截取字串
      if(start>=end) return "None2";
      std::string desc = html_content.substr(start,end-start);
      desc+="...";
      return desc;
      
    }
  };
}
